package com.bai.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.bai.base.exceptionHandler.BaiException;
import com.bai.edu.entity.Subject;
import com.bai.edu.entity.excel.SubjectData;
import com.bai.edu.service.SubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Component;


public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    public SubjectService subjectService;

    public SubjectExcelListener(SubjectService subjectService) {
        this.subjectService = subjectService;
    }

    public SubjectExcelListener() {
    }

    //TODO:读取数据
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null) {
            throw new BaiException(20001, "数据不能为空");
        }
        Subject existedOneSubject = this.existOneSubject(subjectService, subjectData.getOneSubjectName());
        if (existedOneSubject == null) {
            existedOneSubject = new Subject();
            existedOneSubject.setParentId("0");
            existedOneSubject.setTitle(subjectData.getOneSubjectName());
            subjectService.save(existedOneSubject);
        }
        //获取一级分类的id值
        String pid = existedOneSubject.getId();
        Subject existedTwoSubject = this.existTwoSubject(subjectService, subjectData.getTwoSubjectName(), pid);

        if (existedTwoSubject == null) {
            existedTwoSubject = new Subject();
            existedTwoSubject.setParentId(pid);
            existedTwoSubject.setTitle(subjectData.getTwoSubjectName());
            subjectService.save(existedTwoSubject);
        }

    }

    //TODO:一级分类不能重复
    private Subject existOneSubject(SubjectService subjectService, String name) {
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", "0");
        Subject onesubject = subjectService.getOne(wrapper);
        return onesubject;
    }

    //TODO:二级分类不能重复
    private Subject existTwoSubject(SubjectService subjectService, String name, String pid) {
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", pid);
        Subject twosubject = subjectService.getOne(wrapper);
        return twosubject;
    }

    //TODO:读取后执行
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
